/**
 * Alipay.com Inc.
 * Copyright (c) 2004-2013 All Rights Reserved.
 */
package com.pingan.mobilegw.core.service.util;

import com.pingan.mobilegw.adapterservice.model.CacheSession;
import com.pingan.mobilegw.core.model.ServiceConfig;
import com.pingan.mobilegw.core.model.constant.ContextConstant;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * @author jinwenxiang
 * @version $Id: ContextUtil.java, v 0.1 2013-12-17 下午3:19:26 jinwenxiang Exp $
 */
public class ContextUtil {

    /**
     * 获取CacheSession
     * 
     * @param request
     * @return
     */
    public static CacheSession getCacheSession(HttpServletRequest request) {
        return (CacheSession) request.getAttribute(ContextConstant.CACHE_SESSION);
    }

    /**
     * 设置CacheSession
     * 
     * @param request
     * @param session
     */
    public static void setCacheSession(HttpServletRequest request, CacheSession session) {
        request.setAttribute(ContextConstant.CACHE_SESSION, session);
    }

    /**
     * 获取请求的服务配置信息
     * 
     * @param request
     * @return
     */
    public static ServiceConfig getServiceConfig(HttpServletRequest request) {
        return (ServiceConfig) request.getAttribute(ContextConstant.SERVICE_CONFIG);
    }

    /**
     * 设置服务配置信息到上下文中
     * 
     * @param request
     * @param serviceConfig
     */
    public static void setServiceConfig(HttpServletRequest request, ServiceConfig serviceConfig) {
        request.setAttribute(ContextConstant.SERVICE_CONFIG, serviceConfig);
    }

    /**
     * 标记异步开始
     * 
     * @param request
     */
    public static void setAsyncStarting(HttpServletRequest request) {
        setTag(request, ContextConstant.ASYNC_STARTING);
    }

    /**
     * 该请求是否开启异步
     * 
     * @param request
     * @return
     */
    public static boolean isAsyncStarting(HttpServletRequest request) {
        return is(request, ContextConstant.ASYNC_STARTING);
    }

    /**
     * async开启，并且没有抱错
     * 
     * @param request
     * @return
     */
    public static boolean isAsyncStarted(HttpServletRequest request) {
        return request.isAsyncStarted() && !is(request, ContextConstant.AYSNC_ERROR);
    }

    /**
     * 打标到request的attribute中
     * 
     * @param request
     * @param key
     */
    public static void setTag(HttpServletRequest request, String key) {
        request.setAttribute(key, true);
    }

    /**
     * 是否打标
     * 
     * @param request
     * @param key
     * @return
     */
    public static boolean is(HttpServletRequest request, String key) {
        Boolean flag = (Boolean) request.getAttribute(key);
        return (flag == null) ? false : flag;
    }

}
